package com.qiantu.phone.ui.activity;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.hjq.base.DensityUtils;
import com.hjq.http.listener.HttpCallback;
import com.hjq.toast.ToastUtils;
import com.qiantu.api.entity.HouseBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.utils.TextViewLinesUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

public class TransferAnimationActivity extends AppActivity {

    private ConstraintLayout contentView;
    private TextView tvHint1;
    private TextView tvCongratulations1;
    private View btnStart;
    private String videoPath;
    private SurfaceView surfaceView;//layout新加SurfaceView
    private MediaPlayer mediaPlayer;//要在SurfaceView里去创建Media
    private boolean isDestroyed = false;
    private boolean hasPlay = false;
    private float startY;
    private float endY1;
    private float endY2;
    private static final int REFRESH_TIME = 990;
    private String congratulations;
    private int textPadding;
    private List<TextView> tvCongratulationsLists;
    private int perLineHeight;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_transfer_animation;
    }

    @Override
    protected void initView() {
        overridePendingTransition(R.anim.anim_fade_in, R.anim.anim_fade_out);
        contentView = findViewById(R.id.content_view);
        tvHint1 = findViewById(R.id.tv_hint1);
        tvCongratulations1 = findViewById(R.id.tv_congratulations1);
        surfaceView = findViewById(R.id.surface_view);
        btnStart = findViewById(R.id.btn_start);
        btnStart.setEnabled(false);
        setOnClickListener(R.id.btn_start);
        congratulations = getString("congratulations");
//        congratulations = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqr";
        startY = getResources().getDimension(R.dimen.dp_195);
        endY1 = getResources().getDimension(R.dimen.dp_88);
        endY2 = getResources().getDimension(R.dimen.dp_125);
        textPadding = getResources().getDimensionPixelSize(R.dimen.dp_18);
        perLineHeight = getResources().getDimensionPixelSize(R.dimen.dp_20);
        videoPath = "android.resource://" + getPackageName() + "/" + R.raw.transfer_animation;
        surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(@NonNull SurfaceHolder holder) {
                if(mediaPlayer == null){
                    mediaPlayer = new MediaPlayer();
                    try {
                        mediaPlayer.setDataSource(TransferAnimationActivity.this, Uri.parse(videoPath));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    mediaPlayer.setVideoScalingMode(MediaPlayer.VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING);
                    mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                        @Override
                        public void onPrepared(MediaPlayer mp) {
                            if (!mediaPlayer.isPlaying()) {
                                if(isDestroyed){
                                    isDestroyed = false;
                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                                        mediaPlayer.seekTo(10000, MediaPlayer.SEEK_CLOSEST);// SEEK_CLOSEST 移动到最近的一帧
                                    }else{
                                        mediaPlayer.seekTo(10000);// SEEK_CLOSEST 移动到最近的一帧
                                    }
                                }else{
                                    postDelayed(mRefreshRunnable, REFRESH_TIME / 2);
                                    mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                                        @Override
                                        public void onCompletion(MediaPlayer mp) {
                                            removeCallbacks(mRefreshRunnable);
                                        }
                                    });
                                    mediaPlayer.start();
                                }
                            }
                        }
                    });
                    mediaPlayer.setDisplay(holder);
                    mediaPlayer.prepareAsync();
                }
            }

            @Override
            public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {

            }

            @Override
            public void surfaceDestroyed(@NonNull SurfaceHolder holder) {
                if(mediaPlayer != null){
                    isDestroyed = true;
                    mediaPlayer.release();
                    mediaPlayer = null;
                }
            }
        });
        initCongratulationsView();
    }

    private void initCongratulationsView(){
        if(TextUtils.isEmpty(congratulations)){
            return;
        }
        tvCongratulations1.setText(congratulations);
        String[] lineTexts = TextViewLinesUtil.getTextViewLineTexts(tvCongratulations1, DensityUtils.getScreenWidth(getContext()));
        tvCongratulations1.setText(lineTexts[0]);
        tvCongratulationsLists = new ArrayList<>();
        tvCongratulationsLists.add(tvCongratulations1);
        for(int i=1; i<lineTexts.length; i++){
            TextView textView = new TextView(getContext());
            textView.setPadding(textPadding, 0, textPadding, 0);
            textView.setTextColor(0xffffffff);
            textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
            textView.setAlpha(0);
            textView.setGravity(Gravity.CENTER_HORIZONTAL);
            textView.setText(lineTexts[i]);
            ConstraintLayout.LayoutParams cl = new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.MATCH_PARENT, ConstraintLayout.LayoutParams.WRAP_CONTENT);
            cl.topToTop = ConstraintLayout.LayoutParams.PARENT_ID;
            cl.leftToLeft = ConstraintLayout.LayoutParams.PARENT_ID;
            cl.rightToRight = ConstraintLayout.LayoutParams.PARENT_ID;
            contentView.addView(textView, 2 + i, cl);
            tvCongratulationsLists.add(textView);
        }
        startY = endY1 + (endY2 - endY1) + getResources().getDimensionPixelSize(R.dimen.dp_30) + perLineHeight * lineTexts.length;
    }

    @Override
    protected void initData() {
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_start:
                String houseSerialNo = getString("houseSerialNo");
                String loginToken = null;
                if(AppApplication.getInstance().getLoginInfo() != null){
                    loginToken = AppApplication.getInstance().getLoginInfo().getToken();
                }
                LLHttpManager.editDefaultHouse(this, loginToken, houseSerialNo, new HttpCallback<HttpData<Void>>(this) {
                    @Override
                    public void onStart(Call call) {
                        showDialog();
                    }

                    @Override
                    public void onSucceed(HttpData<Void> result) {
                        HouseBean houseBean = new HouseBean();
                        houseBean.setHouseSerialNo(houseSerialNo);
                        AppApplication.getInstance().setCurHouseInfo(houseBean);
                        AppApplication.getInstance().changeHouseData((AppActivity) getActivity(), getString(R.string.init_house_info));
                    }

                    @Override
                    public void onFail(Exception e) {
                        ToastUtils.show(e.getMessage());
//                        finish();
                    }

                    @Override
                    public void onEnd(Call call) {
                        hideDialog();
                    }
                });
                break;
        }
    }

    @Override
    public void onBackPressed() {

    }

    /**
     * 刷新任务
     */
    private final Runnable mRefreshRunnable = new Runnable() {

        @Override
        public void run() {
            postDelayed(this, REFRESH_TIME);
            if (!hasPlay && mediaPlayer != null && mediaPlayer.getCurrentPosition() > 8000) {
                hasPlay = true;
                AnimatorSet animatorSet = new AnimatorSet();
                animatorSet.setInterpolator(new LinearInterpolator());
                animatorSet.setDuration(650);
                animatorSet.playTogether(ObjectAnimator.ofFloat(tvHint1, "translationY", startY, endY1), ObjectAnimator.ofFloat(tvHint1, "alpha", 0f, 1f));
                animatorSet.start();
                if(!TextUtils.isEmpty(tvCongratulations1.getText())){
                    startNextAnimator();
                }else{
                    animatorSet.addListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            btnStart.setEnabled(true);
                        }
                    });
                }
            }
        }
    };


    private int index = 0;
    private void startNextAnimator(){
        getHandler().postDelayed(new Runnable() {
            @Override
            public void run() {
                TextView textView = tvCongratulationsLists.get(index);
                AnimatorSet animatorSet = new AnimatorSet();
                animatorSet.setInterpolator(new LinearInterpolator());
                animatorSet.setDuration(500 + index * 100);
                animatorSet.playTogether(ObjectAnimator.ofFloat(textView, "translationY", startY, endY2 + index * perLineHeight), ObjectAnimator.ofFloat(textView, "alpha", 0f, 1f));
                animatorSet.start();
                index++;
                if(index < tvCongratulationsLists.size() && !TextUtils.isEmpty(tvCongratulationsLists.get(index).getText())){
                    startNextAnimator();
                }else{
                    index = 0;
                    animatorSet.addListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            btnStart.setEnabled(true);
                        }
                    });
                }
            }
        }, 300);
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.anim_fade_in, R.anim.anim_fade_out);
    }

    @Override
    protected boolean isStatusBarDarkFont() {
        return false;
    }
}